import React, { useState, useRef, useEffect, memo } from 'react';
import { useReactMediaRecorder } from 'react-media-recorder';
import { Button, message, Image } from 'antd';
import { SvgIcon } from '@/components/icon';

// import axios from 'axios';
import axios, { CancelToken, isCancel } from 'axios';
import { useDebounceFn } from 'ahooks';

import '../styles/record.css';

import useWindowWidth from '@/hooks/event/use-window-width';
import { useConfig } from '@/store/configStore';
import { useTranslation } from 'react-i18next';

const Dictaphone = ({ onStop, onSwitch, isMessageSend, onInterrupt, onSTT, className }) => {
  const { t } = useTranslation();

  const [isRecording, setIsRecording] = useState(false);
  const [isTranslate, setIsTranslate] = useState(false);
  const isCanceledRef = useRef(false);
  const [startY, setStartY] = useState(null);
  const startTimeRef = useRef<number | null>(null);
  const recordingRef = useRef(false);
  const [isCancelArea, setIsCancelArea] = useState(false); // 用于标识是否在取消区域
  const [cancelTokenSource, setCancelTokenSource] = useState(null);

  const { isPc } = useWindowWidth();

  // const { type, id, sid } = useParams();
  const { id } = useConfig();
  const [currentIconIndex, setCurrentIconIndex] = useState(0);

  const iconNUmber = 20;

  const icons = Array.from({ length: iconNUmber }, (_, index) => (
    <SvgIcon key={index + 1} icon={`ic_rj_${index + 1}`} color="#fff" size={150} />
  ));

  useEffect(() => {
    let timerId: any;

    if (isRecording) {
      timerId = setInterval(() => {
        setCurrentIconIndex(Math.floor(Math.random() * iconNUmber));
      }, 100);
    } else {
      clearInterval(timerId);
    }

    return () => {
      timerId && clearInterval(timerId);
    };
  }, [isRecording]);

  const sendRequest = async (formData) => {
    const source = axios.CancelToken.source();
    setCancelTokenSource(source);
    try {
      setIsTranslate(true);
      onSTT(0);
      const response = await axios.post('/api/ruigpt/v1/audio/doTranscriptions', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
        cancelToken: source.token,
      });

      if (response.data?.data) {
        let data = response.data?.data;
        if (!data) {
          message.warning(t('page.homePage.voiceRefresh'));
          onSTT(2);
          return;
        }

        if (
          data.includes('明镜与点点') ||
          data.includes('普通话中文的句子') ||
          data.includes('这些语言是不可能的') ||
          data.includes('李宗盛') ||
          data.includes('请不吝点赞')
        ) {
          message.warning(t('page.homePage.voiceRefresh'));
          onSTT(2);
          return;
        }

        onStop && !isCanceledRef.current && onStop(data) && onSTT(1);
      }
    } catch (error) {
      onSTT(2);
      if (isCancel(error)) {
        console.log('Request canceled', error.message);
      } else {
        console.error('Error transcribing audio:', error);
        message.warning(t('page.homePage.voiceRefresh'));
      }
    } finally {
      setIsTranslate(false);
      setCancelTokenSource(null); // 重置 cancelTokenSource
    }
  };

  const { startRecording, stopRecording, mediaBlobUrl, status } = useReactMediaRecorder({
    audio: true,
    onStop: async (blobUrl, blob) => {
      if (isCanceledRef.current) {
        isCanceledRef.current = false;
        return;
      }
      if (isMessageSend) {
        message.info(t('page.homePage.onResWait'));
        return;
      }
      let duration = 0;
      if (startTimeRef.current !== null) {
        duration = Date.now() - startTimeRef.current; // 计算录音时长
        if (duration < 600) {
          message.warning(t('page.homePage.shortTime'));
          return;
        }
        console.log(duration);
      }

      if (!id) {
        return;
      }

      if (blob?.size === 0) {
        message.warning(t('page.homePage.voiceRefreshv2'));
        return;
      }

      let durationString = Math.ceil(duration * 0.001).toString();

      const formData = new FormData();
      formData.append('file', blob, 'recording.wav');
      formData.append('appId', id);
      formData.append('duration', durationString);

      sendRequest(formData);

      // const source = axios.CancelToken.source();
      // setCancelTokenSource(source);

      // try {
      //   setIsTranslate(true);
      //   onSTT(0);
      //   const response = await axios.post('/api/ruigpt/v1/audio/doTranscriptions', formData, {
      //     headers: {
      //       'Content-Type': 'multipart/form-data',
      //     },
      //   });

      //   if (response.data?.data) {
      //     let data = response.data?.data;
      //     if (!data) {
      //       message.warning('未识别到语音结果，请重新尝试');
      //       onSTT(2);
      //       return;
      //     }

      //     if (
      //       data.includes('明镜与点点') ||
      //       data.includes('普通话中文的句子') ||
      //       data.includes('这些语言是不可能的') ||
      //       data.includes('词曲 李宗盛')
      //     ) {
      //       // message.warning('语音识别结果包含敏感内容，请重新尝试');
      //       message.warning('未识别到语音结果，请重新尝试');
      //       onSTT(2);
      //       return;
      //     }

      //     onStop && !isCanceledRef.current && onStop(data) && onSTT(1);
      //   }
      // } catch (error) {
      //   onSTT(2);
      //   console.error('Error transcribing audio:', error);
      //   message.warning('未识别到语音结果，请重新尝试');
      // } finally {
      //   console.log('ppppp')
      //   setIsTranslate(false);
      //   setCancelTokenSource(null);
      // }
    },
  });

  const checkMicrophonePermission = async () => {
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
      stream.getTracks().forEach((track) => track.stop()); // 停止获取的媒体流
      return true;
    } catch (error) {
      console.error('Microphone permission denied:', error);
      message.error(t('page.homePage.getVoiceErr'));
      return false;
    }
  };
  useEffect(() => {
    const testMicroPhone = async () => {
      await checkMicrophonePermission();
    };
    testMicroPhone();
    // document.addEventListener('mousemove', handleMouseMove);
    // document.addEventListener('mouseup', handleMouseUp);
    // return ()=>{
    //   document.removeEventListener('mousemove', handleMouseMove);
    //   document.removeEventListener('mouseup', handleMouseUp);
    // }
  }, []);

  const { run } = useDebounceFn(
    () => {
      setIsRecording(true);
      recordingRef.current = true;
      startRecording();
      startTimeRef.current = Date.now(); // 记录开始时间
      try {
        if ('vibrate' in navigator) {
          navigator.vibrate(500);
        }
      } catch (err) { }
    },
    {
      wait: 500,
    },
  );

  const start = async () => {
    console.log(status);
    if (recordingRef.current) return; // 如果已经在录音，则不执行

    console.log('start');
    try {
      navigator.vibrate(300);
    } catch (err) { }

    setIsRecording(true);
    recordingRef.current = true;
    startRecording();
    startTimeRef.current = Date.now(); // 记录开始时间
  };

  const stop = () => {
    console.log(status);
    if (!recordingRef.current) return; // 如果不在录音，则不执行

    console.log('stop');
    setIsRecording(false);
    recordingRef.current = false;
    stopRecording();
  };

  const cancel = () => {
    if (!recordingRef.current) return; // 如果不在录音，则不执行

    console.log('cancel');
    message.info(t('page.homePage.voiceCancel'));
    isCanceledRef.current = true;
    setIsRecording(false);
    recordingRef.current = false;
    stopRecording();
  };

  useEffect(() => {
    console.log(status, isRecording);
    if (status == 'recording' && isRecording == false) {
      setIsRecording(false);
      recordingRef.current = false;
      stopRecording();
    }
  }, [isRecording, status]);

  useEffect(() => {
    if (status == 'stopped') {
      setIsRecording(false);
      recordingRef.current = false;
    }
  }, [status]);

  const handleTouchStart = (e) => {
    e.preventDefault(); // 阻止默认行为
    e.stopPropagation();
    if (e.touches && e.touches.length > 0) {
      setStartY(e.touches[0].clientY);
      start();
    }
  };

  const handleTouchMove = (e) => {
    e.preventDefault(); // 阻止默认行为
    e.stopPropagation();
    if (startY !== null && e.touches && e.touches.length > 0) {
      const currentY = e.touches[0].clientY;
      const distance = startY - currentY;
      console.log(distance);
      if (distance > 100) {
        setIsCancelArea(true); // 进入取消区域
      } else {
        setIsCancelArea(false); // 离开取消区域
      }
    }
  };

  const handleTouchEnd = (e) => {
    e.preventDefault(); // 阻止默认行为
    e.stopPropagation();
    if (recordingRef.current) {
      if (isCancelArea) {
        cancel();
      } else {
        stop();
      }
    }
    setStartY(null);
    setIsCancelArea(false); // 重置取消区域状态
  };

  // useEffect(() => {}, [isCancelArea]);

  const handleInterrupt = () => {
    console.log('handleInterrupt');
    if (cancelTokenSource) {
      cancelTokenSource.cancel('Operation canceled by the user.');
      setCancelTokenSource(null); // 重置 cancelTokenSource
    }
    onInterrupt();
    setIsTranslate(false);
  };

  const handleMouseMove = (e) => {
    e.preventDefault(); // 阻止默认行为
    e.stopPropagation();
    console.log(startY);
    if (startY !== null) {
      const currentY = e.clientY;
      const distance = startY - currentY;
      console.log(distance);
      if (distance > 100) {
        setIsCancelArea(true); // 进入取消区域
      } else {
        setIsCancelArea(false); // 离开取消区域
      }
    }
  };

  const handleMouseUp = (e) => {
    e.preventDefault(); // 阻止默认行为
    e.stopPropagation();
    console.log('handleMouseUp', e.clientY, startY);
    if (recordingRef.current) {
      if (isCancelArea) {
        cancel();
      } else {
        stop();
      }
    }
    setStartY(null);
    setIsCancelArea(false); // 重置取消区域状态
  };

  const handleMouseDown = (e) => {
    console.log('handleMouseDown', e.clientY, startY);
    e.preventDefault(); // 阻止默认行为
    e.stopPropagation();
    setStartY(e.clientY);
    start();
  };

  return (
    <>
      <div
        style={{
          position: 'relative',
          width: '100%',
          height: '100%',
          display: 'flex',
          alignItems: 'center',
        }}
      >
        <div
          style={{
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            flex: 1,
            // marginLeft: isPc ? '0px' : '20px',
            // marginRight: isPc ? '0px' : '20px',
            marginBottom: isPc ? '0px' : '20px',
            // marginLeft: '20px',
            // marginRight: '20px',
            // marginBottom: '20px',
          }}
        >
          <Button
            onContextMenu={(e) => e.preventDefault()}
            // onMouseDown={handleMouseDown}
            // onMouseUp={handleMouseUp}
            // onMouseLeave={handleMouseUp}
            // loading={isTranslate}
            onMouseDown={start}
            onMouseUp={stop}
            onMouseLeave={cancel}
            // onMouseMove={cancel}
            onTouchStart={handleTouchStart}
            onTouchEnd={handleTouchEnd}
            onTouchCancel={cancel}
            onTouchMove={handleTouchMove}
            className="no-select no-touch h-full w-full select-none"
            style={{
              height: '45px',
              backgroundColor: isCancelArea ? '#E24747' : 'var(--brand-color)',
              // borderColor: isCancelArea ? '#E24747' : '#6640FF',
              // outline: isCancelArea ? '3px solid #E24747' : '3px solid #6640FF',
              // backgroundColor: isRecording ? (isCancelArea ? '#E24747' : '#E8EAF2') : '#6640FF',
              color: isRecording ? '#474C5F' : '#fff',
              borderRadius: '16px',
              userSelect: 'none', // 禁用文本选择
              // touchAction: 'manipulation', // 禁用默认触摸行为
              fontSize: '13px',
              fontWeight: 550,
              zIndex: 100,
              touchAction: 'none',
            }}
            icon={isRecording ? icons[currentIconIndex] : undefined}
          // icon={
          //   isRecording ? (
          //     // <Image src={Voice} height={80} width={200} preview={false} style={{ userSelect: 'none', touchAction: 'none' }}/>
          //     <>
          //       <SvgIcon icon="ic_rj_soundwave" color="#fff" size={60} />
          //       <SvgIcon icon="ic_rj_soundwave" color="#fff" size={60} />
          //       <SvgIcon icon="ic_rj_soundwave" color="#fff" size={60} />
          //     </>
          //   ) : undefined
          // }
          >
            {isRecording ? ' ' : t('page.homePage.holdTalk')}
          </Button>
        </div>
        {!isRecording && (
          <Button
            type="text"
            icon={
              isMessageSend ? (
                <SvgIcon icon="ic_stop" color="#fff" size={25} />
              ) : (
                <SvgIcon icon="ic_rj_keyboard" color="#fff" size={25} />
              )
            }
            onClick={isMessageSend ? handleInterrupt : onSwitch}
            style={{
              borderRadius: '16px',
              width: isPc ? '60px' : '50px',
              display: 'flex',
              justifyContent: 'center',
              alignItems: 'center',
              position: 'absolute',
              right: '5px',
              background: 'rgba(255, 255, 255, 0.2)',
              zIndex: 200,
              // marginLeft: isPc ? '0px' : '20px',
              // marginRight: isPc ? '0px' : '20px',
              marginBottom: isPc ? '0px' : '20px',
              // marginLeft: '20px',
              // marginRight: '20px',
              // marginBottom: '20px',
            }}
          />
        )}

        {isRecording && isPc && (
          <>
            <div
              style={{
                position: 'absolute',
                bottom: 0,
                left: 0,
                width: '100%',
                height: '200px',
                background: 'rgba(255, 255, 255, 0.7)',
                borderRadius: '200% 200% 0 0 / 100% 100% 0 0',
              }}
            />
            <div
              style={{
                position: 'absolute',
                bottom: 0,
                left: 0,
                width: '100%',
                height: '240px',
                background: 'rgba(255, 255, 255, 0.4)',
                borderRadius: '200% 200% 0 0 / 100% 100% 0 0',
              }}
            />
            <div
              style={{
                position: 'absolute',
                bottom: '100%',
                left: '50%',
                transform: 'translate(-50%, -50%)',
                color: '#A39BC4',
                fontSize: '16px',
                fontWeight: 550,
                zIndex: 100,
              }}
            >
              {isCancelArea ? t('page.homePage.releaseCancel') : t('page.homePage.releaseCancelv2')}
            </div>
          </>
        )}
      </div>

      {isRecording && !isPc && (
        <>
          <div
            style={{
              position: 'absolute',
              bottom: 0,
              left: 0,
              width: '100%',
              height: '200px',
              background: 'rgba(255, 255, 255, 0.7)',
              borderRadius: '200% 200% 0 0 / 100% 100% 0 0',
              zIndex: 0,
            }}
          />
          <div
            style={{
              position: 'absolute',
              bottom: 0,
              left: 0,
              width: '100%',
              height: '240px',
              background: 'rgba(255, 255, 255, 0.4)',
              borderRadius: '200% 200% 0 0 / 100% 100% 0 0',
              zIndex: 0,
            }}
          />
          <div
            style={{
              position: 'absolute',
              bottom: isPc ? '15%' : '80px',
              left: '50%',
              transform: 'translate(-50%, -50%)',
              color: '#A39BC4',
              fontSize: '16px',
              fontWeight: 550,
              zIndex: 1,
            }}
          >
            {isCancelArea ? t('page.homePage.releaseCancel') : t('page.homePage.releaseCancelv2')}
          </div>
        </>
      )}
    </>
  );
};

export default memo(Dictaphone);
